import axios from "axios";
import router from "../router";
import qs from "qs";
axios.defaults.timeout = 10000; //请求超时10秒axios.defaults.baseURL = '/user';
//请求base url 每个接口前都有带这个，考虑到前端测试处理跨域axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//设置post请求是的header信息
// 用到session验证码功能，让请求携带cookie，可以加上以下一行axios.defaults.withCredentials = true
//http request 拦截器
// axios.defaults.baseURL = "/api";
axios.interceptors.request.use(
  config => {
    let token = sessionStorage.getItem("token");
    if (token) {
      // 判断是否存在token，如果存在的话，则每个http header都加上token
      // config.headers = {
      //   "jwttoken": token
      // };
    }
    config.headers = {
      "Content-Type": "application/json;charset=utf-8"
    };
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);
// 拦截器
axios.interceptors.response.use(
  response => {
    if (response.headers.jwttoken) {
      sessionStorage.setItem("token", response.headers.jwttoken);
    }
    if (response.data.code === 4003) {
      Toast({
        mes: "您没有权限操作！",
        timeout: 1500,
        callback: () => {
          router.go(-1);
        }
      });
      return false;
    }
    if (response.data.code === -1) {
      localStorage.removeItem("token");
    }
    return response;
  },
  err => {
    if (err.code === "ECONNABORTED" && err.message.indexOf("timeout") !== -1) {
      Toast({ mes: "网络异常，连接超时...", timeout: 1500 });
    }
    return Promise.reject(err);
  }
);
// get请求
export function get(url, params = {}, headers = {}) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params,
        headers: headers
      })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err);
      });
  });
}
// post请求
export function post(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, params).then(
      response => {
        resolve(response.data);
      },
      err => {
        reject(err);
      }
    );
  });
}
// postForm请求
export function postForm(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, qs.stringify(params)).then(
      response => {
        resolve(response.data);
      },
      err => {
        reject(err);
      }
    );
  });
}
